new Vue({
    el: '#app',
    data: {
        chatHistory: [],
        conversations: [],
        currentConversation: null, // 当前选中的对话
        usernameDb: '',
        passwordDb: '',
        displayedUsername: '开始', // 新增的变量
        dbUploadedFileName: '', // 用于存储上传的文件名
        urlDb: '',
        databaseName: '',
        inputMessage: '',
        username: '',
        showMenu: false,
        showLogin: false,
        showDatabase: false,
        menuVisible: false,
        isLoggedIn: false,
        password: '',
        connectedDatabases: [],
        sourceDocuments: [], // 新增用于存储来源文档
        showDocumentModal: false, // 控制文档内容弹窗的显示
        currentDocument: null, // 当前选中的文档
        showRegister: false,
        registerUsername: '',
        registerPassword: '',
        localUsers: [], // 用于存储本地用户数据
        isLoading: false, // 新增的加载状态
    },
    mounted() {
        // 从 localStorage 获取数据库登录信息
        this.urlDb = localStorage.getItem('db_url') || '';
        this.usernameDb = localStorage.getItem('db_username') || '';
        this.passwordDb = localStorage.getItem('db_password') || '';

        // 更新用户名到页面
        const usernameDisplay = document.getElementById('username-display');
        if (usernameDisplay) {
            usernameDisplay.textContent = this.username;
        }

        // 初始化时加载已保存的数据库列表
        try {
            this.connectedDatabases = JSON.parse(localStorage.getItem('connected_databases')) || [];
        } catch (error) {
            this.connectedDatabases = [];
        }

        // 加载当前用户的对话历史
        this.loadChatHistory();
        this.localUsers = JSON.parse(localStorage.getItem('localUsers')) || [];
    },
    updated() {
        this.$nextTick(() => {
            this.currentConversation.messages.forEach((message, index) => {
                if (message.chart && !message.chart.rendered) {
                    console.log(`正在渲染消息索引为 ${index} 的图表`);
                    const chartRef = this.$refs[`chart-${index}`];
                    if (chartRef && chartRef.length > 0) {
                        const chartDom = chartRef[0];
                        console.log(`图表 DOM 尺寸: ${chartDom.clientWidth}x${chartDom.clientHeight}`);
                        // 初始化 ECharts 实例，并应用主题（如有）
                        const myChart = echarts.init(chartDom, 'macarons'); // 如果没有使用主题，可以省略第二个参数
                        myChart.setOption(message.chart.option);
                        myChart.resize(); // 调整图表大小
                        // 标记图表为已渲染，避免重复初始化
                        this.$set(this.currentConversation.messages[index].chart, 'rendered', true);
                        console.log(`图表已渲染: chart-${index}`);
                    } else {
                        console.log(`未找到图表引用: chart-${index}`);
                    }
                }
            });
        });
    },
    methods: {
        addInitialMessage() {
            const initialMessage = {
                text: "你好，我是心语智能对话数据报表助手，请问有什么可以帮助您的吗？",
                user: false,
                isTable: false,
                chart: null,
                sourceDocument: null
            };
            this.currentConversation.messages.push(initialMessage);
            this.saveChatHistory();
        },
        scrollToBottom() {
            const chatMessages = this.$refs.chatMessages;
            if (chatMessages) {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        },
        loadChatHistory() {
            if (this.isLoggedIn && this.username !== '开始') {
                const storedConversations = JSON.parse(localStorage.getItem(`conversations_${this.username}`)) || [];
                this.conversations = storedConversations;
                if (this.conversations.length > 0) {
                    this.currentConversation = this.conversations[0];
                    // 如果当前对话没有消息，添加初始消息
                    if (this.currentConversation.messages.length === 0) {
                        this.addInitialMessage();
                    }
                } else {
                    // 如果没有对话，自动创建一个默认对话
                    this.addNewConversation('默认对话');
                }
            } else {
                if (this.conversations.length > 0) {
                    this.currentConversation = this.conversations[0];
                    // 如果当前对话没有消息，添加初始消息
                    if (this.currentConversation.messages.length === 0) {
                        this.addInitialMessage();
                    }
                } else {
                    // 如果没有对话，自动创建一个默认对话
                    this.addNewConversation('默认对话');
                }
            }
        },
        saveChatHistory() {
            if (this.username && this.username !== '开始') {
                localStorage.setItem(`conversations_${this.username}`, JSON.stringify(this.conversations));
            }
        },
        addNewConversation(name) {
            const newConv = {
                id: Date.now() + Math.random(), // 添加唯一 ID
                name: name || `对话${this.conversations.length + 1}`,
                messages: []
            };
            this.conversations.push(newConv);
            this.currentConversation = newConv;
            this.saveChatHistory();
        },
        deleteConversation(index) {
            if (this.conversations.length === 1) {
                // 使用 SweetAlert2 显示警告消息
                Swal.fire({
                    title: '提示',
                    text: '必须至少保留一个对话',
                    icon: 'warning'
                });
            } else {
                // 使用 SweetAlert2 显示确认对话框
                Swal.fire({
                    title: '确认删除',
                    text: `确定要删除对话 "${this.conversations[index].name}" 吗？`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    reverseButtons: true,
                })
                    .then((result) => {
                        if (result.isConfirmed) {
                            // 如果要删除的是当前对话，切换到另一个对话
                            const isCurrent = this.currentConversation === this.conversations[index];
                            this.conversations.splice(index, 1);
                            this.saveChatHistory();

                            if (isCurrent) {
                                if (this.conversations.length > 0) {
                                    this.currentConversation = this.conversations[0];
                                } else {
                                    this.currentConversation = null;
                                }
                            }

                            // 使用 SweetAlert2 显示删除成功的消息
                            Swal.fire({
                                title: '已删除!',
                                text: '对话已被删除。',
                                icon: 'success'
                            });
                        }
                    });
            }
        },
        addConversationPrompt() {
            Swal.fire({
                title: '请输入新对话的名称',
                input: 'text',
                inputValue: `对话${this.conversations.length + 1}`,
                showCancelButton: true,
                confirmButtonText: '创建',
                cancelButtonText: '取消',
                inputValidator: (value) => {
                    if (!value) {
                        return '对话名称不能为空!';
                    }
                    if (this.conversations.some(conv => conv.name === value)) {
                        return '该对话名称已存在，请选择其他名称。';
                    }
                    return null;
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    this.addNewConversation(result.value);
                    Swal.fire('成功', '新对话已创建。', 'success');
                }
            });
        },
        renameConversation(index) {
            Swal.fire({
                title: '请输入新的对话名称:',
                input: 'text',
                inputValue: this.conversations[index].name,
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValidator: (value) => {
                    if (!value) {
                        return '对话名称不能为空!';
                    }
                    if (this.conversations.some((conv, idx) => conv.name === value && idx !== index)) {
                        return '该对话名称已存在，请选择其他名称。';
                    }
                    return null;
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    this.updateConversationName(index, result.value);
                    Swal.fire('成功', '对话名称已更新。', 'success');
                }
            });
        },
        updateConversationName(index, newName) {
            if (newName && this.conversations[index]) {
                this.conversations[index].name = newName;
                this.saveChatHistory();
            }
        },
        selectConversation(conv) {
            this.currentConversation = conv;
        },
        saveDatabaseConfig() {
            // 保存数据库配置到 localStorage
            localStorage.setItem('db_url', this.urlDb);
            localStorage.setItem('db_username', this.usernameDb);
            localStorage.setItem('db_password', this.passwordDb);
            Swal.fire('成功', '数据库配置已保存', 'success');

            // 同时保存已连接的数据库列表
            localStorage.setItem('connected_databases', JSON.stringify(this.connectedDatabases));
        },
        addDatabase() {
            // 使用 localStorage 中的账号密码进行添加数据库操作
            if (!this.databaseName) {
                Swal.fire({
                    icon: 'error',
                    title: '错误',
                    text: '请输入数据库名称'
                });
                return;
            }

            const params = new URLSearchParams([
                ['url', this.urlDb],
                ['username', this.usernameDb],
                ['password', this.passwordDb],
                ['database', this.databaseName]
            ]);

            fetch(`http://localhost:8080/Database/AddDatabase?${params.toString()}`, {
                method: 'GET', // 保留 GET 方法
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded' // 因为我们现在使用查询字符串
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        Swal.fire('成功', '数据库添加成功', 'success');

                        // 添加到前端数据库列表
                        this.connectedDatabases.push({
                            name: this.databaseName,
                            url: this.urlDb,
                            username: this.usernameDb,
                            password: this.passwordDb
                        });

                        // 清空输入框
                        this.databaseName = '';

                        // 同时保存已连接的数据库列表
                        localStorage.setItem('connected_databases', JSON.stringify(this.connectedDatabases));
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: '错误',
                            text: '数据库添加失败: ' + data.msg
                        });
                    }
                })
                .catch(error => {
                    Swal.fire({
                        icon: 'error',
                        title: '错误',
                        text: '请求失败: ' + error.message
                    });
                });
        },
        removeDatabase(databaseName) {
            // 使用 localStorage 中的账号密码进行删除数据库操作
            if (!databaseName) {
                Swal.fire({
                    icon: 'error',
                    title: '错误',
                    text: '无法识别要删除的数据库名称'
                });
                return;
            }

            // 构建查询参数
            const params = new URLSearchParams([
                ['url', this.urlDb],
                ['username', this.usernameDb],
                ['password', this.passwordDb],
                ['database', databaseName]
            ]);

            // 将查询参数附加到URL上
            fetch(`http://localhost:8080/Database/RemoveDatabase?${params.toString()}`, {
                method: 'GET', // 更改为 GET 方法
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded' // 这一行实际上不需要，因为我们没有请求体
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        Swal.fire('成功', '数据库删除成功', 'success');

                        // 从前端数据库列表中移除
                        this.connectedDatabases = this.connectedDatabases.filter(db => db.name !== databaseName);

                        // 同时保存已连接的数据库列表
                        localStorage.setItem('connected_databases', JSON.stringify(this.connectedDatabases));
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: '错误',
                            text: '数据库删除失败: ' + data.msg
                        });
                    }
                })
                .catch(error => {
                    Swal.fire({
                        icon: 'error',
                        title: '错误',
                        text: '请求失败: ' + error.message
                    });
                });
        },
        // 打开文档内容
        openDocument(doc) {
            this.currentDocument = doc;
            this.showDocumentModal = true;
        },

        // 关闭文档内容模态框
        closeDocumentModal() {
            this.showDocumentModal = false;
            this.currentDocument = null;
        },
        async sendMessage() {
            if (this.inputMessage.trim() !== '') {
                // 将用户输入的消息添加到当前对话中
                this.currentConversation.messages.push({
                    text: this.inputMessage,
                    user: true,
                    isTable: false,
                    chart: null,
                    sourceDocument: null // 初始化为 null
                });
                this.saveChatHistory();

                const userMessage = this.inputMessage;
                this.inputMessage = '';

                // 添加加载消息
                const loadingMessage = {
                    text: '正在思考...',
                    user: false,
                    isLoading: true, // 标记为加载中
                    isTable: false,
                    chart: null,
                    sourceDocument: null
                };
                this.currentConversation.messages.push(loadingMessage);
                this.saveChatHistory();

                // 自动滚动到底部
                this.$nextTick(() => {
                    this.scrollToBottom();
                });

                try {
                    const response = await fetch('http://localhost:8080/textAnalysis', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ message: userMessage })
                    });

                    if (!response.ok) {
                        throw new Error(`Server error: ${response.statusText}`);
                    }

                    const responseData = await response.json();

                    // 假设 responseData 包含 answer、fileName 和 fileContent
                    const { answer, fileName, fileContent } = responseData;

                    if (fileName && fileContent && answer) {
                        // 处理 answer
                        this.processAnswer(answer, userMessage);

                        // 附加 sourceDocument 到最后一条消息
                        const lastMessageIndex = this.currentConversation.messages.length - 1;
                        if (lastMessageIndex >= 0) {
                            this.$set(this.currentConversation.messages[lastMessageIndex], 'sourceDocument', {
                                name: fileName,
                                content: fileContent
                            });
                        }

                        this.saveChatHistory();
                    } else {
                        // 仅处理 answer
                        this.processAnswer(answer, userMessage);
                    }

                } catch (error) {
                    console.error('Error:', error);
                    // 替换加载消息为错误消息
                    const loadingMsgIndex = this.currentConversation.messages.findIndex(msg => msg.isLoading);
                    if (loadingMsgIndex !== -1) {
                        this.currentConversation.messages.splice(loadingMsgIndex, 1, {
                            text: `Error: ${error.message}`,
                            user: false,
                            isLoading: false,
                            isTable: false,
                            chart: null,
                            sourceDocument: null
                        });
                        this.saveChatHistory();
                    }
                }
            }
        },
        processAnswer(answer, userMessage) {
            // 假设 answer 是一个 JSON 字符串，需要解析
            let answerData;
            try {
                answerData = JSON.parse(answer);
            } catch (error) {
                console.log('Answer is not a JSON string, treating as plain text.');
                this.currentConversation.messages.push({
                    text: answer,
                    user: false,
                    isTable: false,
                    chart: null,
                    sourceDocument: null
                });
                this.saveChatHistory();
                return;
            }

            // 检查是否需要绘制图表
            const shouldDrawChart = userMessage.includes('图') ||
                userMessage.includes('柱状图') ||
                userMessage.includes('饼图') ||
                userMessage.includes('折线图');

            if (shouldDrawChart && Array.isArray(answerData) && answerData.length > 0) {
                // 确定图表类型
                let chartType = 'bar'; // 默认柱状图
                if (userMessage.includes('饼图')) {
                    chartType = 'pie';
                } else if (userMessage.includes('折线图')) {
                    chartType = 'line';
                }

                // 生成图表配置
                const chartOption = this.generateChartOption(chartType, answerData);
                console.log('Generated Chart Option:', JSON.stringify(chartOption, null, 2));

                // 将图表配置添加到消息中
                this.currentConversation.messages.push({
                    text: '',
                    user: false,
                    isTable: false,
                    chart: { type: chartType, option: chartOption, rendered: false },
                    sourceDocument: null
                });
                this.saveChatHistory();

            } else if (Array.isArray(answerData) && answerData.length > 0) {
                // 动态生成表格
                const tableHeaders = Object.keys(answerData[0]);
                let tableHTML = `
            <table class="table table-bordered table-striped table-hover table-sm custom-table">
                <thead class="thead-dark">
                    <tr>
        `;
                tableHeaders.forEach(header => {
                    tableHTML += `<th>${header}</th>`;
                });
                tableHTML += `
                    </tr>
                </thead>
                <tbody>
        `;
                answerData.forEach(row => {
                    tableHTML += `<tr>`;
                    tableHeaders.forEach(header => {
                        tableHTML += `<td>${row[header]}</td>`;
                    });
                    tableHTML += `</tr>`;
                });
                tableHTML += `</tbody></table>`;

                // 将表格作为消息推送，并标记为表格
                this.currentConversation.messages.push({
                    text: tableHTML,
                    user: false,
                    isTable: true,
                    chart: null,
                    sourceDocument: null
                });
                this.saveChatHistory();
            } else if (typeof answerData === 'object' && answerData !== null) {
                // 将对象作为普通文本显示
                this.currentConversation.messages.push({
                    text: JSON.stringify(answerData, null, 2),
                    user: false,
                    isTable: false,
                    chart: null,
                    sourceDocument: null
                });
                this.saveChatHistory();
            } else {
                this.currentConversation.messages.push({
                    text: 'No data available or invalid JSON response.',
                    user: false,
                    isTable: false,
                    chart: null,
                    sourceDocument: null
                });
                this.saveChatHistory();
            }
        },
        showLoginDialog() {
            this.showLogin = true;
            this.showMenu = false; // 隐藏选择框
        },
        showDatabaseConfig() {
            if (!this.isLoggedIn) {
                Swal.fire({
                    icon: 'info',
                    title: '提示',
                    text: '请先登录'
                });
                return;
            }
            this.showDatabase = true;
            this.showMenu = false; // 隐藏选择框
        },
        showRegisterDialog() {
            this.showRegister = true;
            this.menuVisible = false;
        },
        // 注册功能
        handleRegister() {
            // 检查用户名是否已存在
            if (this.localUsers.some(user => user.username === this.registerUsername)) {
                Swal.fire({
                    icon: 'error',
                    title: '错误',
                    text: '用户名已存在！'
                });
                return;
            }

            // 添加新用户到本地存储
            this.localUsers.push({
                username: this.registerUsername,
                password: this.registerPassword
            });
            localStorage.setItem('localUsers', JSON.stringify(this.localUsers));

            // 清空表单并关闭弹窗
            this.registerUsername = '';
            this.registerPassword = '';
            this.showRegister = false;

            Swal.fire('成功', '注册成功！', 'success');
        },
        logout() {
            this.isLoggedIn = false;
            this.showMenu = false; // 隐藏选择框
            window.location.reload(true); // 强制从服务器重新加载
        },
        async handleLogin(event) {
            // 首先检查本地用户
            const localUser = this.localUsers.find(user =>
                user.username === this.username && user.password === this.password
            );

            if (localUser) {
                // 本地用户验证成功
                this.loginSuccess();
                return;
            }

            try {
                // 如果本地验证失败，尝试后端验证
                const response = await fetch('http://localhost:8080/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        user_name: this.username,
                        password: this.password
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }

                const data = await response.json();

                if (data.code === 1 && data.msg === "success") {
                    this.loginSuccess();
                } else {
                    this.loginFailed();
                }
            } catch (error) {
                console.error("登录错误:", error);
                this.loginFailed();
            }
        },
        loginSuccess() {
            localStorage.setItem('username', this.username);
            this.isLoggedIn = true;
            this.showLogin = false;

            // 更新显示的用户名
            this.displayedUsername = this.username; // 只在登录成功后更新

            Swal.fire('成功', '登录成功！', 'success');
            this.loadChatHistory();
        },

        loginFailed() {
            Swal.fire({
                icon: 'error',
                title: '错误',
                text: '登录失败，请检查用户名或密码'
            });
        },
        toggleMenu(event) {
            this.menuVisible = !this.menuVisible;
            if (this.menuVisible) {
                document.addEventListener('click', this.handleClickOutside);
            } else {
                document.removeEventListener('click', this.handleClickOutside);
            }
        },

        handleClickOutside(event) {
            const menu = this.$refs.menu; // 参考菜单元素
            const avatar = event.target.closest('.user-info'); // 参考头像元素
            if (menu && !menu.contains(event.target) && !avatar) {
                this.menuVisible = false;
                document.removeEventListener('click', this.handleClickOutside);
            }
        },
        // 生成 ECharts 配置的方法
        generateChartOption(type, data) {
            if (!Array.isArray(data) || data.length === 0) {
                console.error('Invalid data for chart generation.');
                return {};
            }

            const keys = Object.keys(data[0]);
            if (keys.length < 2) {
                console.error('Data does not have enough keys for chart generation.');
                return {};
            }

            const categories = data.map(item => item[keys[0]]);
            const values = data.map(item => item[keys[1]]);
            console.log('Categories:', categories);
            console.log('Values:', values);

            // 定义颜色主题
            const colorPalette = ['#5470C6', '#91CC75', '#EE6666', '#FAC858', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC'];

            let option = {
                color: colorPalette,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow' // 改为阴影指示器
                    },
                    backgroundColor: 'rgba(50,50,50,0.7)',
                    textStyle: {
                        color: '#fff'
                    }
                },
                legend: {
                    textStyle: {
                        color: '#333'
                    },
                    top: '10%' // 确保图例位于顶部
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%', // 增加底部留白以放置标题
                    containLabel: true
                },
                series: []
            };

            switch (type) {
                case 'bar':
                    option.title = {
                        text: '柱状图',
                        left: 'center',
                        bottom: '5%', // 设置标题位于底部
                        textStyle: {
                            color: '#333',
                            fontSize: 18
                        }
                    };
                    option.xAxis = {
                        type: 'category',
                        data: categories,
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        }
                    };
                    option.yAxis = {
                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        },
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        }
                    };
                    option.series.push({
                        name: keys[1],
                        type: 'bar',
                        data: values,
                        itemStyle: {
                            barBorderRadius: [5, 5, 0, 0],
                            shadowColor: 'rgba(0,0,0,0.1)',
                            shadowBlur: 10
                        },
                        label: {
                            show: true,
                            position: 'top',
                            color: '#333',
                            fontWeight: 'bold'
                        }
                    });
                    break;
                case 'pie':
                    option.title = {
                        text: '饼图',
                        left: 'center',
                        bottom: '5%', // 设置标题位于底部
                        textStyle: {
                            color: '#333',
                            fontSize: 18
                        }
                    };
                    option.tooltip = {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)',
                        backgroundColor: 'rgba(50,50,50,0.7)',
                        textStyle: {
                            color: '#fff'
                        }
                    };
                    // 饼图不需要x轴和y轴
                    delete option.xAxis;
                    delete option.yAxis;
                    option.series.push({
                        name: keys[1],
                        type: 'pie',
                        radius: '50%',
                        data: data.map(item => ({ name: item[keys[0]], value: item[keys[1]] })),
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        label: {
                            formatter: '{b}: {c} ({d}%)',
                            color: '#333',
                            fontWeight: 'bold'
                        }
                    });
                    break;
                case 'line':
                    option.title = {
                        text: '折线图',
                        left: 'center',
                        bottom: '5%', // 设置标题位于底部
                        textStyle: {
                            color: '#333',
                            fontSize: 18
                        }
                    };
                    option.xAxis = {
                        type: 'category',
                        data: categories,
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        }
                    };
                    option.yAxis = {
                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: '#999'
                            }
                        },
                        axisLabel: {
                            color: '#666'
                        },
                        splitLine: {
                            lineStyle: {
                                type: 'dashed'
                            }
                        }
                    };
                    option.tooltip = {
                        trigger: 'axis',
                        backgroundColor: 'rgba(50,50,50,0.7)',
                        textStyle: {
                            color: '#fff'
                        }
                    };
                    option.series.push({
                        name: keys[1],
                        type: 'line',
                        data: values,
                        smooth: false, // 平滑曲线
                        symbol: 'circle',
                        symbolSize: 8,
                        lineStyle: {
                            width: 3
                        },
                        areaStyle: {
                            color: 'rgba(84, 112, 198, 0.2)'
                        },
                        itemStyle: {
                            color: '#5470C6'
                        },
                        label: {
                            show: true,
                            position: 'top',
                            color: '#333',
                            fontWeight: 'bold'
                        }
                    });
                    break;
                default:
                    console.error('Unsupported chart type:', type);
            }

            console.log('Chart Option:', option);
            return option;
        },
        async handleFileUpload(event) {
            const file = event.target.files[0]; // 获取上传的文件
            if (file) {
                console.log('File uploaded:', file.name);

                // 显示上传中的状态
                const loadingSwal = Swal.fire({
                    title: '文件上传中...',
                    html: `正在上传文件: ${file.name}`,
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // 创建 FormData 用于上传文件
                const formData = new FormData();
                formData.append('file', file); // 将文件添加到 formData

                try {
                    // 使用 fetch 上传文件到后端接口
                    const response = await fetch('http://localhost:8080/embedding', {
                        method: 'POST',
                        body: formData // 发送 FormData，包含文件
                    });

                    // 关闭加载提示
                    await loadingSwal.close();

                    if (response.ok) {
                        // 添加成功接收文件的消息到聊天记录
                        this.currentConversation.messages.push({ text: `已接收文件: ${file.name}`, user: false, isTable: false, chart: null });

                        // 可选：获取服务器返回的文本信息
                        // const resultText = await response.text();
                        // this.messages.push({ text: resultText, user: false, isTable: false, chart: null });

                        // 显示成功提示
                        Swal.fire({
                            icon: 'success',
                            title: '上传成功',
                            text: ` ${file.name} 上传成功！`,
                            timer: 2000, // 2秒后自动关闭
                            showConfirmButton: false
                        });
                    } else {
                        console.error('Server error:', response.statusText);
                        this.currentConversation.messages.push({ text: '文件上传失败，服务器错误。', user: false, isTable: false, chart: null });

                        // 显示失败提示
                        Swal.fire({
                            icon: 'error',
                            title: '上传失败',
                            text: '文件上传失败，服务器错误。'
                        });
                    }
                } catch (error) {
                    // 关闭加载提示
                    await loadingSwal.close();

                    console.error('Fetch error:', error);
                    this.currentConversation.messages.push({ text: '网络错误，文件上传失败。', user: false, isTable: false, chart: null });

                    // 显示网络错误提示
                    Swal.fire({
                        icon: 'error',
                        title: '上传失败',
                        text: '网络错误，文件上传失败。'
                    });
                }
            }
        },
        triggerDbFileUpload() {
            this.$refs.dbFileInput.click();
        },
        async handleDbFileUpload(event) {
            const file = event.target.files[0];
            if (file) {
                console.log('上传的文件:', file);


                // 显示上传中的状态
                const loadingSwal = Swal.fire({
                    title: '文件上传中...',
                    html: `正在上传数据库结构文件: ${file.name}`,
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // 创建 FormData 用于上传文件
                const formData = new FormData();
                formData.append('file', file);

                try {
                    // 使用 fetch 上传文件到后端接口
                    const response = await fetch('http://localhost:8080/File/InformationExtraction', {
                        method: 'POST',
                        body: formData
                    });

                    // 关闭加载提示
                    await loadingSwal.close();

                    if (response.ok) {
                        Swal.fire({
                            icon: 'success',
                            title: '上传成功',
                            text: `数据库结构文件 ${file.name} 上传成功！`,
                            timer: 2000, // 2秒后自动关闭
                            showConfirmButton: false
                        });
                        this.dbUploadedFileName = file.name;
                    } else {
                        console.error('Server error:', response.statusText);
                        Swal.fire({
                            icon: 'error',
                            title: '上传失败',
                            text: '数据库结构文件上传失败，服务器错误'
                        });
                    }
                } catch (error) {
                    // 关闭加载提示
                    await loadingSwal.close();

                    console.error('Fetch error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '上传失败',
                        text: '网络错误，数据库结构文件上传失败'
                    });
                }
            }
        },
    },
    watch: {
        // 监听 currentConversation 的变化，确保视图更新
        currentConversation(newConv) {
            // 由于我们直接在模板中绑定 currentConversation.messages，无需额外操作
        },
        // 移除对 messages 的深度监听
    }
});
